package dao.User;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;

import model.User;
import abstractFactory.Factory;

public class UserDAOJPA implements UserDAO{
	EntityManager manager;
	EntityManagerFactory fact;
	
	public EntityManager getManager() {
		if(manager == null) {
			manager = Factory.getFactory().createEntityManager();
		}
		return manager;
	}
	
	public boolean create(User user){
		getManager().getTransaction().begin();			
		getManager().persist(user);
		getManager().getTransaction().commit();
		getManager().close();
		return true;
	}
	public List<User> listAll(){
		getManager().getTransaction().begin();
		Query query = (Query) getManager().createQuery("SELECT u FROM User u where u.active = 1" );
		@SuppressWarnings("unchecked")
		List<User> users = query.getResultList();
		getManager().close();
		return users;
	}
	public Long totalUsers(){
		getManager().getTransaction().begin();
		Query query = (Query) getManager().createQuery("SELECT count(u) FROM User u where u.active = 1" );
		Long total = (Long) query.getSingleResult();
		getManager().close();
		return total;
	}
	public User logUser(String name, String pass){
		try {
			getManager().getTransaction().begin();
			Query query = (Query) getManager().createQuery("SELECT u FROM User u where u.login = :n and u.password = :p" );
			query.setParameter("n", name);
			query.setParameter("p", pass);
			User user = (User) query.getSingleResult();
			getManager().close();
			if(user != null)
				return user;
			else
				return null;
		} 
		catch (Exception e) {	
			return null;				
		}
	}
	public boolean update(User user){
		getManager().getTransaction().begin();
		getManager().merge(user);
		getManager().getTransaction().commit();
		getManager().close();
		return true;
	}
	public boolean delete(User user){
		getManager().getTransaction().begin();
		getManager().remove(user);
		getManager().getTransaction().commit();
		getManager().close();				
		return true;
	}
	public User list(int id){
		getManager().getTransaction().begin();
		User user = getManager().find(User.class, id);
		getManager().close();			
		return user;
	}
}
